// https://lbs.qq.com/webApi/javascriptGL/glDoc/docIndexMap#2
import { ref, onBeforeUnmount } from 'vue'
import { getImageUrl } from '@/utils/tool.js'
export function useTMap() {
  const map = ref(null)
  const markerLayer = ref(null)
  const scriptLoaded = ref(false)

  // 加载腾讯地图脚本
  const loadMapScript = () => {
    return new Promise((resolve, reject) => {
      if (scriptLoaded.value) {
        resolve(TMap) // 如果脚本已经加载，直接resolve
        return
      }
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src =
        'https://map.qq.com/api/gljs?v=1.exp&key=WCMBZ-OEXKT-YK3XV-LO6XN-LFLM7-Y7B7P'
      script.onload = () => {
        scriptLoaded.value = true
        resolve(TMap) // 脚本加载成功
      }
      script.onerror = () => {
        reject(new Error('Failed to load TMap script')) // 脚本加载失败
      }
      document.head.appendChild(script)
    })
  }

  // 初始化地图，外部通过调用此方法并传递参数
  const initMap = (
    containerId,
    center = [23.165105, 113.429126],
    zoom = 8,
    viewMode = '2D',
  ) => {
    return loadMapScript().then(() => {
      map.value = new TMap.Map(containerId, {
        pitch: 45,
        zoom,
        viewMode,
        center: new TMap.LatLng(center[0], center[1]),
        showControl: false,
      })
    })
  }
  // 清理地图实例
  onBeforeUnmount(() => {
    if (map.value) {
      map.value.destroy()
      map.value = null
    }
  })
  // point
  const initPoint = (
    point = {
      latitude: '',
      longitude: '',
    },
  ) => {
    return new TMap.LatLng(point.latitude, point.longitude)
  }
  // 设置中心点
  const setCenter = (
    center = {
      latitude: 39.984104,
      longitude: 116.307503,
    },
  ) => {
    if (!map.value) return
    map.value.setCenter(new TMap.LatLng(center.latitude, center.latitude))
  }
  // 获取地图中心
  const getCenter = () => {
    if (!map.value) return
    return map.value.getCenter()
  }
  // 设置缩放级别
  const setZoom = (zoom = 12) => {
    if (!map.value) return
    map.value.setZoom(zoom)
  }

  /**
   * 添加多个点标记到地图上的函数。
   * @param {Array<Object>} points - 包含每个标记点位信息的数组
   * @param {Function} eventHandler - 点击标记的事件处理函数
   */
  const addMarkers = (points = [], eventHandler) => {
    if (!map.value || !points.length) return

    // 如果标记层未初始化，初始化它
    if (!markerLayer.value) {
      markerLayer.value = new TMap.MultiMarker({
        map: map.value,
      })
      markerLayer.value.on('click', eventHandler)
    }

    // 添加新的标记点
    markerLayer.value.add(
      points.map((point) => {
        console.log('🚀 ~ file:useTMap method: line:105 -----', point.id + '')
        return {
          id: point.id + '',
          position: new TMap.LatLng(point.latitude, point.longitude),
          properties: point,
        }
      }),
    )
  }
  /**
   * 移除标记
   * @param {Array<String>} points - 点标记id数组
   */
  const removeMarkers = (points = []) => {
    if (!markerLayer.value) return

    if (points.length) {
      markerLayer.value.remove()
    } else {
      markerLayer.value.setMap(null)
      markerLayer.value = null // 清空标记层
    }
  }

  return {
    map,
    initMap,
    setCenter,
    getCenter,
    setZoom,
    addMarkers,
    removeMarkers,
  }
}
